package com.ss6621.spring1.Controller;

import com.ss6621.spring1.Service.UserService;
import com.ss6621.spring1.pojo.User;
import com.ss6621.spring1.utils.JwtUtils;
import com.ss6621.spring1.utils.Result;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/auth")

public class AuthController {
    @Resource
    private  AuthenticationManager authenticationManager;
    @Resource
    private  JwtUtils jwtUtils;
    @Resource
    private  UserService userService;



    @PostMapping("/login")
    public Result<String> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtUtils.generateToken(username);
        return Result.success(token);
    }
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        if (userService.findByUsername(user.getUsername()) != null) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }
        User newUser = userService.register(user);
        return ResponseEntity.ok(newUser);
    }
    //修改信息
    @PreAuthorize("#user.id == authentication.principal.id ")
    @PostMapping("/update")
    public ResponseEntity<?> update(@RequestBody User user) {
        log.info("update user: {}", user);
        return ResponseEntity.ok(userService.update(user));
    }


}
